package cn.rkylin.oms.warehouse.shiporder.service;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.rkylin.oms.goods.domain.GoodsSku;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.goods.vo.SkuStockVO;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.dao.IOrderSkuDAO;
import cn.rkylin.oms.order.vo.OrderSkuVO;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.shop.dao.ShopDAOImpl;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.storage.dao.IStorDAO;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.vo.StorVO;
import cn.rkylin.oms.warehouse.shiporder.adapter.ShiporderAdapter;
import cn.rkylin.oms.warehouse.shiporder.adapter.ShiporderFactory;
import cn.rkylin.oms.warehouse.shiporder.request.ConsignShipOrderRequest;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.resend.dao.IAfterSaleResendDAO;
import cn.rkylin.oms.aftersale.resend.dao.IAfterSaleResendSkuDAO;
import cn.rkylin.oms.aftersale.resend.service.IAfterSaleResendService;
import cn.rkylin.oms.aftersale.resend.vo.ResendVO;
import cn.rkylin.oms.common.consts.ResendCancelStatus;
import cn.rkylin.oms.common.consts.ShiporderCancelStatus;
import cn.rkylin.oms.common.consts.ShiporderStatus;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.push.request.PushTradeOfflineSend;
import cn.rkylin.oms.warehouse.shiporder.dao.ShiporderDAOImpl;
import cn.rkylin.oms.warehouse.shiporder.dao.ShiporderSkuDAOImpl;
import cn.rkylin.oms.warehouse.shiporder.domain.Shiporder;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderSkuVO;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import cn.rkylin.oms.warehouse.stock.service.IStockService;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;

/**
 * 发货Service
 *
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Repository(value = "shiporderService")
public class ShiporderServiceImpl extends ApolloService implements IShiporderService {

    @Value("${oms.address}")
    private String omsAddres;

    @Value("${job.address}")
    private String jobAddress;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ShiporderDAOImpl shiporderDAOImpl;

    @Autowired
    private ShiporderSkuDAOImpl shiporderSkuDAOImpl;

    @Autowired
    private ProjectManagerService projectService;

    @Autowired
    public IOrderService orderService;

    @Autowired
    private IStockService stockService;

    @Autowired
    public IAfterSaleResendService resendService;

    @Autowired
    ShopDAOImpl shopDAO;

    @Autowired
    private IOrderSkuDAO orderSkuDAO;

    @Autowired
    private IOrderDAO orderDAO;

    @Autowired
    private IStorDAO storDAO;
    
    /**
     * resendDAO:补发单数据访问层.
     */
    @Autowired
    public IAfterSaleResendDAO resendDAO;
    
    /**
     * 查询发货单列表
     *
     * @param page        页号
     * @param rows        页大小
     * @param shiporderVO 发货单VO
     * @return 发货单列表
     * @throws Exception 异常
     */
    @SuppressWarnings("rawtypes")
    public PageInfo findByWhere(int page, int rows, ShiporderVO shiporderVO) throws Exception {
        PageInfo<ShiporderVO> shiporderVOList = findPage(page, rows, "pageSelectShiporder", shiporderVO);
        return shiporderVOList;
    }

    /**
     * 查询发货单列表
     *
     * @param page        页号
     * @param rows        页大小
     * @param shiporderVO 发货单VO
     * @return 发货单列表
     * @throws Exception 异常
     */
    @SuppressWarnings("rawtypes")
    public PageInfo findByWhereLocal(int page, int rows, ShiporderVO shiporderVO) throws Exception {
        PageInfo<ShiporderVO> shiporderVOList = findPage(page, rows, "pageSelectLocalShiporder", shiporderVO);
        return shiporderVOList;
    }

    /**
     * 查询发货单列表
     *
     * @param page        页号
     * @param rows        页大小
     * @param shiporderVO 发货单VO
     * @return 发货单列表
     * @throws Exception 异常
     */
    @SuppressWarnings("rawtypes")
    public PageInfo findByWhereForOrder(int page, int rows, ShiporderVO shiporderVO) throws Exception {
        PageInfo<ShiporderVO> shiporderVOList = findPage(page, rows, "pageSelectShiporderForOrder", shiporderVO);
        return shiporderVOList;
    }

    /**
     * 查询发货单列表
     *
     * @param page        页号
     * @param rows        页大小
     * @param shiporderVO 发货单VO
     * @return 发货单列表
     * @throws Exception 异常
     */
    @SuppressWarnings("rawtypes")
    public PageInfo findByWhereForOrderNoStorType(int page, int rows, ShiporderVO shiporderVO) throws Exception {
        PageInfo<ShiporderVO> shiporderVOList = findPage(page, rows, "pageSelectShiporderForOrderNoStorType", shiporderVO);
        return shiporderVOList;
    }

    @Override
    public Map<String, Object> updateShiporder(ShiporderVO shiporderVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        // 收货人不能为空
        if (StringUtils.isBlank(shiporderVO.getCons())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "收货人不能为空");
            return returnMap;
        }

        // 固定电话与手机至少要输入一个
        if (StringUtils.isBlank(shiporderVO.getConsTel()) && StringUtils.isBlank(shiporderVO.getConsMobile())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "固定电话与手机至少要输入一个 手机");
            return returnMap;
        }

        // 收货人地址不能为空
        if (StringUtils.isBlank(shiporderVO.getConsAddr())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "收货人地址不能为空");
            return returnMap;
        }
        shiporderDAOImpl.update(shiporderVO);

        returnMap.put("success", "y");
        return returnMap;
    }

    /**
     * 查询发货单信息
     *
     * @param shiporderVO 发货单VO
     * @return 发货单信息
     * @throws Exception 异常
     */
    public ShiporderVO getShiporderInfo(ShiporderVO shiporderVO) throws Exception {
        return shiporderDAOImpl.getShiporderInfo(shiporderVO);
    }

    /**
     *批量系统发货
     * @param shiporderVOList
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> batchSystemSend(List<ShiporderVO> shiporderVOList) throws Exception {
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        if (shiporderVOList!=null && shiporderVOList.size()>0){
            String errorMsg = "";
            for (int i = 0 ; i < shiporderVOList.size() ; i++){
                ShiporderVO shipOrderUpdate = shiporderVOList.get(i);
                ShiporderVO shiporderData = new ShiporderVO();
                shiporderData.setShiporderId(shipOrderUpdate.getShiporderId());
                ShiporderVO shiporderInfo = shiporderDAOImpl.getShiporderInfo(shiporderData);

                if (StringUtils.isBlank(shiporderInfo.getLgstNo())){
                    errorMsg = errorMsg + "发货单：" + shiporderInfo.getShiporderCode()+"，物流单号不能为空；\\n";
                    continue;
                }
                shipOrderUpdate.setShipStatus("y");
                shipOrderUpdate.setShipTime(new Date());

                String dockingKingdee = projectService.getCurrentPrjDockingKingdee();

                ShiporderSkuVO shiporderSkuData = new ShiporderSkuVO();
                shiporderSkuData.setShiporderId(shipOrderUpdate.getShiporderId());
                List<ShiporderSkuVO> shiporderSkuInfoList = shiporderSkuDAOImpl.selectShiporderSkuList(shiporderSkuData);

                //更新库存
                boolean flg = false;
                for (ShiporderSkuVO shiporderSkuInfo : shiporderSkuInfoList) {
                    int qty = Integer.parseInt(shiporderSkuInfo.getQty());

                    StockVO stock = stockService.getStock(shiporderInfo.getEntId(), shiporderInfo.getPrjId(), shiporderSkuInfo.getSkuId(), shiporderInfo.getStorId());
                    if (stock != null && stock.getStockQty() != null) {
                        if (stock.getStockQty() < qty) {
                            errorMsg = errorMsg + "发货单：" + shiporderInfo.getShiporderCode()+ ","+stock.getSkuCode()+"库存数不足；\\n";
                            flg = true;
                        } else {
                            GoodsSku goodsSkuTemp = goodsService.getGoodsSkuBySkuId(shiporderSkuInfo.getSkuId());
                            shiporderSkuInfo.setGoodsSkuCost(goodsSkuTemp.getCostPrice());
                            shiporderSkuDAOImpl.updateShipOrderSkuById(shiporderSkuInfo);

                            OrderSkuVO sysOrderSkuUpdate = orderSkuDAO.selectByPrimaryKeyOrderSku(shiporderSkuInfo.getOrderSkuId());
                            int shippingQty = sysOrderSkuUpdate.getShippingQty()==null?0:sysOrderSkuUpdate.getShippingQty();
                            int shipedQty = sysOrderSkuUpdate.getShipedQty()==null?0:sysOrderSkuUpdate.getShipedQty();
                            sysOrderSkuUpdate.setShippingQty(shippingQty-Integer.valueOf(shiporderSkuInfo.getQty()));
                            sysOrderSkuUpdate.setShipedQty(shipedQty+Integer.valueOf(shiporderSkuInfo.getQty()));
                            sysOrderSkuUpdate.setOrderSkuId(shiporderSkuInfo.getOrderSkuId());
                            sysOrderSkuUpdate.setGoodsSkuCost(goodsSkuTemp.getCostPrice());
                            sysOrderSkuUpdate.setUpdateTime(new Date());
                            orderSkuDAO.update(sysOrderSkuUpdate);

                            if (YesNoConst.NO.equals(dockingKingdee)) {
                                StockVO stockVO = new StockVO();
                                stockVO.setEntId(shiporderInfo.getEntId());
                                stockVO.setSkuId(shiporderSkuInfo.getSkuId());
                                stockVO.setStorId(shiporderInfo.getStorId());
                                stockVO.setSourceCode(shiporderInfo.getShiporderCode());
                                stockVO.setTag("本地仓系统发货");

                                stockVO.setStockQty(qty * -1);
                                stockVO.setAllotQty(qty * -1);
                                stockService.updateStock(stockVO);
                            }
                        }
                    } else {
                        errorMsg = errorMsg + shiporderSkuInfo.getSkuCode()+ "规格商家编码商品可发货数不足；\\n";
                    }
                }
                if (!flg){
                    Map<String, String> paramMap = new HashMap<String, String>();
                    paramMap.put("sourceId",shiporderInfo.getSourceId());
                    // 补发单的情况
                    if (shiporderInfo.getSourceType().equals("rs")) {
                    	ResendVO rVO = resendDAO.selectDetailByPrimaryKey(shiporderInfo.getSourceId());
                    	rVO.setResendStatus("z");
                    	rVO.setUpdateTime(new Date());
                        resendDAO.updateByPrimaryKeySelective(rVO);
                    } else {
                    	// 系统订单的情况
                        if (shiporderDAOImpl.shipedByOrderIdCount(paramMap)<=0){
                            List<OrderSkuVO> list = orderSkuDAO.selectByOrderIdSysOrderSkuQty(shiporderInfo.getSourceId());

                            OrderVO orderVO = new OrderVO();
                            orderVO.setOrderId(shiporderInfo.getSourceId());
                            orderVO.setLgstNo(shiporderInfo.getLgstNo());
                            orderVO.setLgstId(shiporderInfo.getLgstId());
                            orderVO.setLgstName(shiporderInfo.getLgstName());
                            orderVO.setLgstCode(shiporderInfo.getLgstCode());
                            orderVO.setUpdateTime(new Date());
                            orderVO.setShipTime(new Date());
                            if (list!=null && list.size()>0){
                                if (list.get(0).getQty() - list.get(0).getShipedQty()==0){
                                    orderVO.setOrderStatus("r");
                                }
                            }
                            orderDAO.update(orderVO);
                        } else {
                            List<OrderSkuVO> list = orderSkuDAO.selectByOrderIdSysOrderSkuQty(shiporderInfo.getSourceId());
                            if (list!=null && list.size()>0){
                                if (list.get(0).getQty() - list.get(0).getShipedQty()==0){
                                    OrderVO orderVO = new OrderVO();
                                    orderVO.setOrderId(shiporderInfo.getSourceId());
                                    orderVO.setUpdateTime(new Date());
                                    orderVO.setOrderStatus("r");
                                    orderDAO.update(orderVO);
                                }
                            }
                        }
                    }
                    shiporderDAOImpl.update(shipOrderUpdate);
                }
            }
            if (StringUtils.isNotBlank(errorMsg)){
                returnJSON.put("result", "failed");
                returnJSON.put("msg", errorMsg);
            } else {
                returnJSON.put("result", "success");
            }

        } else {
            returnJSON.put("result", "failed");
            returnJSON.put("msg", "没有要系统发货的数据");
        }
        return returnJSON;
    }

    /**
     * 查询发货单信息
     *
     * @param shiporderVO 发货单VO
     * @return 发货单列表
     * @throws Exception 异常
     */
    public List<ShiporderVO> getShiporderList(ShiporderVO shiporderVO) throws Exception {
        return shiporderDAOImpl.getShiporderList(shiporderVO);
    }

    /**
     * 查询发货单商品列表
     *
     * @return 发货单信息
     * @throws Exception 异常
     */
    public List<ShiporderSkuVO> selectShiporderSkuList(ShiporderSkuVO shiporderSkuVO) throws Exception {
        return shiporderSkuDAOImpl.selectShiporderSkuList(shiporderSkuVO);
    }

    public String LocalcancelShiporder(String shiporderId) throws Exception {
        String returnMsg = "";

        ShiporderVO shiporderVO = new ShiporderVO();
        shiporderVO.setShiporderId(shiporderId);
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        // 设置项目Id
        String prjId = currentUser.getCurrentProject().getPrjId();
        shiporderVO.setPrjId(prjId);
        PageInfo<ShiporderVO> shiporderVOList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporderAll", shiporderVO);
        List<ShiporderVO> shiporderDataList = shiporderVOList.getList();

        if (shiporderDataList != null && shiporderDataList.size() > 0) {
            ShiporderVO shiporderData = shiporderDataList.get(0);

            if (ShiporderStatus.WAIT_SEND_OUT_GOODS.equals(shiporderData.getShiporderStatus())
                    || ShiporderStatus.SENDING_OUT_GOODS.equals(shiporderData.getShiporderStatus())) {
                returnMsg = this.localsaveCancelShiporder(shiporderData);
            }
        }

        return returnMsg;
    }

    /**
     * 取消发货单
     *
     * @param shiporderVO 发货单VO
     * @return 取消结果信息
     * @throws Exception 异常
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public String localsaveCancelShiporder(ShiporderVO shiporderVO) throws Exception {
        String returnMsg = "";

            // 得到发库单信息
            ShiporderVO shiporderData = new ShiporderVO();
            shiporderData.setShiporderId(shiporderVO.getShiporderId());
            ShiporderVO shiporderInfo = shiporderDAOImpl.getShiporderInfo(shiporderData);
            // 得到发库单SKU信息
            ShiporderSkuVO shiporderSkuData = new ShiporderSkuVO();
            shiporderSkuData.setShiporderId(shiporderVO.getShiporderId());
            List<ShiporderSkuVO> shiporderSkuInfoList = shiporderSkuDAOImpl.selectShiporderSkuList(shiporderSkuData);

            // 取消发货单
            Shiporder shiporder = new Shiporder();
            shiporder.setShiporderId(shiporderVO.getShiporderId());
            shiporder.setCancelStatus(ShiporderCancelStatus.Y);
            shiporderDAOImpl.updateShiporder(shiporder);

            if ("or".equals(shiporderInfo.getSourceType())) { // 操作订单
                orderService.cancelShiporder(shiporderInfo);
            } else if ("rs".equals(shiporderInfo.getSourceType())) { // 操作补发单
                resendService.updateResendStatusAfterCancelShiporder(shiporderInfo.getSourceId());
            }

            // 更新库存数
            for (ShiporderSkuVO shiporderSkuInfo : shiporderSkuInfoList) {
                StockVO stockVO = new StockVO();
                stockVO.setEntId(shiporderInfo.getEntId());
                stockVO.setSkuId(shiporderSkuInfo.getSkuId());
                stockVO.setStorId(shiporderInfo.getStorId());
                stockVO.setSourceCode(shiporderInfo.getShiporderCode());
                stockVO.setTag("取消发货单(拿走前)");
                int qty = Integer.parseInt(shiporderSkuInfo.getQty());
                stockVO.setUnallotQty(qty);
                stockVO.setAllotQty(qty * -1);
                stockService.updateStock(stockVO);
            }

            returnMsg = "取消成功";

        return returnMsg;
    }

    /**
     * 取消发货单为补发单
     *
     * @param shiporderId 发货单Id
     * @return 取消结果信息
     * @throws Exception 异常
     */
    public String cancelShiporder(String shiporderId) throws Exception {
        String returnMsg = "";

        ShiporderVO shiporderVO = new ShiporderVO();
        shiporderVO.setShiporderId(shiporderId);
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        // 设置项目Id
        String prjId = currentUser.getCurrentProject().getPrjId();
        shiporderVO.setPrjId(prjId);
        PageInfo<ShiporderVO> shiporderVOList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporderAll", shiporderVO);
        List<ShiporderVO> shiporderDataList = shiporderVOList.getList();

        if (shiporderDataList != null && shiporderDataList.size() > 0) {
            ShiporderVO shiporderData = shiporderDataList.get(0);

            if (ShiporderStatus.WAIT_SEND_OUT_GOODS.equals(shiporderData.getShiporderStatus())
                    || ShiporderStatus.SENDING_OUT_GOODS.equals(shiporderData.getShiporderStatus())) {
                returnMsg = this.saveCancelShiporder(shiporderData);
            }
        }

        return returnMsg;
    }

    /**
     * 取消发货单
     *
     * @param shiporderVO 发货单VO
     * @return 取消结果信息
     * @throws Exception 异常
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public String saveCancelShiporder(ShiporderVO shiporderVO) throws Exception {
        String returnMsg = "";

        if (ShiporderStatus.WAIT_SEND_OUT_GOODS.equals(shiporderVO.getShiporderStatus())) {
            // 得到发库单信息
            ShiporderVO shiporderData = new ShiporderVO();
            shiporderData.setShiporderId(shiporderVO.getShiporderId());
            ShiporderVO shiporderInfo = shiporderDAOImpl.getShiporderInfo(shiporderData);
            // 得到发库单SKU信息
            ShiporderSkuVO shiporderSkuData = new ShiporderSkuVO();
            shiporderSkuData.setShiporderId(shiporderVO.getShiporderId());
            List<ShiporderSkuVO> shiporderSkuInfoList = shiporderSkuDAOImpl.selectShiporderSkuList(shiporderSkuData);

            // 取消发货单
            Shiporder shiporder = new Shiporder();
            shiporder.setShiporderId(shiporderVO.getShiporderId());
            shiporder.setCancelStatus(ShiporderCancelStatus.Y);
            shiporderDAOImpl.updateShiporder(shiporder);

            if ("or".equals(shiporderInfo.getSourceType())) { // 操作订单
                orderService.cancelShiporder(shiporderInfo);
            } else if ("rs".equals(shiporderInfo.getSourceType())) { // 操作补发单
                resendService.updateResendStatusAfterCancelShiporder(shiporderInfo.getSourceId());
            }

            // 更新库存数
            for (ShiporderSkuVO shiporderSkuInfo : shiporderSkuInfoList) {
                StockVO stockVO = new StockVO();
                stockVO.setEntId(shiporderInfo.getEntId());
                stockVO.setSkuId(shiporderSkuInfo.getSkuId());
                stockVO.setStorId(shiporderInfo.getStorId());
                stockVO.setSourceCode(shiporderInfo.getShiporderCode());
                stockVO.setTag("取消发货单(拿走前)");
                int qty = Integer.parseInt(shiporderSkuInfo.getQty());
                stockVO.setUnallotQty(qty);
                stockVO.setAllotQty(qty * -1);
                stockService.updateStock(stockVO);
            }

            returnMsg = "取消成功";
        } else if (ShiporderStatus.SENDING_OUT_GOODS.equals(shiporderVO.getShiporderStatus())) {
        	// 得到发库单信息
            ShiporderVO shiporderData = new ShiporderVO();
            shiporderData.setShiporderId(shiporderVO.getShiporderId());
            ShiporderVO shiporderInfo = shiporderDAOImpl.getShiporderInfo(shiporderData);
            if ("y".equals(shiporderInfo.getCancelStatus())) {
            	returnMsg = "取消成功";
            } else {
	            // 调用奇门接口
	            String resJson = HttpUtils.sendByGet(jobAddress + "warehouseDockingController/manualCancelShiporder.action?shiporderVO="
	                    + URLEncoder.encode(JSON.toJSONString(shiporderVO)), null);
	            Map<String, String> resultMap = JSON.parseObject(resJson, Map.class);
	            if ("true".equals(resultMap.get("success"))) {
	                returnMsg = "取消成功";
	            } else {
	                returnMsg = "取消失败";
	            }
            }
        }

        return returnMsg;
    }

    /**
     * 发货单平台发货
     *
     * @param shiporderVO 发货单VO
     * @throws Exception 异常
     */
    private void shiporderConsign(ShiporderVO shiporderVO) throws Exception {
        Shiporder shiporder = new Shiporder();
        shiporder.setShiporderId(shiporderVO.getShiporderId());
        shiporder.setConsignStatus(YesNoConst.YES);
        shiporderDAOImpl.updateShiporder(shiporder);
    }

    /**
     * 系统订单平台发货
     *
     * @param shiporderVO 发货单VO
     * @throws Exception 异常
     */
    private void orderConsign(ShiporderVO shiporderVO) throws Exception {
        OrderVO orderVO = new OrderVO();
        orderVO.setTradeCode(shiporderVO.getTradeCode());
        orderVO.setOrderCode(shiporderVO.getSourceCode());
        orderService.updateOrderForConsign(orderVO);
    }

    /**
     * 平台发货
     *
     * @param shiporderVO 发货单VO
     * @return 取消结果信息
     * @throws Exception 异常
     */
    @SuppressWarnings({"unchecked", "deprecation"})
    public Map<String, String> consign(ShiporderVO shiporderVO) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();

        OrderVO orderData = orderService.getOrderInfoByTradeCode(shiporderVO.getTradeCode());
        // 平台已发货
        if ("EC_TRADE_FINISHED".equals(orderData.getTradeStatus()) || "EC_TRADE_ALL_SEND".equals(orderData.getTradeStatus())) {
            this.shiporderConsign(shiporderVO);

            resultMap.put("success", YesNoConst.YES);
            resultMap.put("msg", "平台已发货");
            return resultMap;
        }
        // 交易已经关闭
        if ("EC_TRADE_CANCELED".equals(orderData.getTradeStatus())) {
            resultMap.put("success", YesNoConst.NO);
            resultMap.put("msg", "交易已经关闭");
            return resultMap;
        }
        // 关联的订单为手动创建不允许平台发货
        if ("其它".equals(orderData.getShopType())) {
            resultMap.put("success", YesNoConst.NO);
            resultMap.put("msg", "关联的订单为手动创建不允许平台发货");
            return resultMap;
        }

        String resJson = "";

        // todo You like you to delete
        ShopVO shopVO = shopDAO.findById(shiporderVO.getShopId());
        ShiporderAdapter shiporderAdapter = ShiporderFactory.getAdapter(shopVO.getShopType());
        if (shiporderAdapter != null) {
            ConsignShipOrderRequest consignShipOrderRequest = new ConsignShipOrderRequest();
            consignShipOrderRequest.setEcTradeCode(shiporderVO.getTradeCode());
            consignShipOrderRequest.setLgstCode(shiporderVO.getLgstCode());
            consignShipOrderRequest.setLgstNo(shiporderVO.getLgstNo());
            resJson = shiporderAdapter.platfromConsign(shopVO.getShopId(), consignShipOrderRequest);
        } else {
            // 校验通过后淘宝平台发货
            PushTradeOfflineSend pushTradeOfflineSend = new PushTradeOfflineSend();
            pushTradeOfflineSend.setShopId(shiporderVO.getShopId());
            pushTradeOfflineSend.setEcTradeCode(shiporderVO.getTradeCode());
            pushTradeOfflineSend.setLgstNo(shiporderVO.getLgstNo());
            pushTradeOfflineSend.setLgstCode(shiporderVO.getLgstCode());
            resJson = HttpUtils.sendByGet(omsAddres + "pushTrade/pushConsign.action?pushTradeOfflineSend="
                    + URLEncoder.encode(JSON.toJSONString(pushTradeOfflineSend)), null);
        }
        resultMap = JSON.parseObject(resJson, Map.class);
        // 系统平台发货
        if (YesNoConst.YES.equals(resultMap.get("success"))) {
            this.shiporderConsign(shiporderVO);
            this.orderConsign(shiporderVO);

            resultMap.put("success", YesNoConst.YES);
            resultMap.put("msg", "平台已发货");
        }
        return resultMap;
    }

    /**
     * 根据退款单锁定发货单
     *
     * @param orderId 订单Id
     * @return 结果信息
     * @throws Exception 异常
     */
    public String lockForSysRefund(String orderId) throws Exception {
        String errMsg = "";

        // 得到发货单信息
        // CurrentUser currentUser =
        // WebContextFactory.getWebContext().getCurrentUser();
        // String prjId = currentUser.getCurrentProject().getPrjId();
        ShiporderVO shiporderVo = new ShiporderVO();
        // shiporderVo.setPrjId(prjId);
        shiporderVo.setSourceId(orderId);
        shiporderVo.setCancelStatus(YesNoConst.NO);
        PageInfo<ShiporderVO> shiporderVoList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporder", shiporderVo);
        List<ShiporderVO> list = shiporderVoList.getList();

        if (list != null && list.size() > 0) {
            for (ShiporderVO shiporderData : list) {
                Shiporder shiporder = new Shiporder();
                shiporder.setShiporderId(shiporderData.getShiporderId());
                if (ShiporderStatus.WAIT_SEND_OUT_GOODS.equals(shiporderData.getShiporderStatus())) { // 待发货
                    shiporder.setLockStatus(YesNoConst.YES);
                    shiporderDAOImpl.updateShiporderLock(shiporder);
                } else if (ShiporderStatus.SENDING_OUT_GOODS.equals(shiporderData.getShiporderStatus())) { // 发货中
                    shiporder.setCancelStatus("r");
                    shiporderDAOImpl.updateShiporder(shiporder);
                }
            }

            errMsg = "";
        } else {
            errMsg = "没有对应发货单数据";
        }

        return errMsg;
    }

    /**
     * 根据订单锁定发货单 by jinshen
     */
    @Override
    public Map<String, String> lock(String orderId) throws Exception {
        Map<String, String> mapResult = new HashMap<String, String>();

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        String prjId = currentUser.getCurrentProject().getPrjId();
        ShiporderVO shiporderVO = new ShiporderVO();
        shiporderVO.setPrjId(prjId);
        shiporderVO.setSourceId(orderId);
        shiporderVO.setSourceType("or");
        shiporderVO.setDeleted("n");
        PageInfo<ShiporderVO> shiporderVOList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporderAll", shiporderVO);
        List<ShiporderVO> list = shiporderVOList.getList();
        if (list != null && list.size() > 0) {
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            for (int i = 0; i < list.size(); i++) {
                ShiporderVO vo = list.get(i);
                if ("n".equals(vo.getCancelStatus())) {
                    if ("n".equals(vo.getHasTaken()) && "n".equals(vo.getShipStatus())) {
                        vo.setLockStatus("y");
                        vo.setLockTime(dateString);
                        vo.setUpdateTime(dateString);
                        Shiporder shiporder = new Shiporder();
                        BeanUtils.copyProperties(vo, shiporder);
                        shiporderDAOImpl.updateShiporderLock(shiporder);
                    } else {
                        vo.setShiporderStatus(ShiporderStatus.SENDING_OUT_GOODS);
                        OrderVO orderVO = new OrderVO();
                        orderVO.setOrderId(orderId);
                        PageInfo<OrderVO> page = orderService.findByWhere(0, Integer.MAX_VALUE, orderVO);
                        vo.setShopId(page.getList().get(0).getShopId());
                        Stor stor = storDAO.findByid(vo.getStorId());
                        if ("ext".equals(stor.getStorType())){
                            this.saveCancelShiporder(vo);
                        }
                    }
                }
            }
            mapResult.put("result", "y");
        } else {
            mapResult.put("result", "y");
        }
        return mapResult;
    }

    /**
     * 解锁发货的 wangxing add 2017-12-9
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> unLock(String orderId) throws Exception {
        Map<String, String> mapResult = new HashMap<String, String>();

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        String prjId = currentUser.getCurrentProject().getPrjId();
        ShiporderVO shiporderVO = new ShiporderVO();
        shiporderVO.setPrjId(prjId);
        shiporderVO.setSourceId(orderId);
        shiporderVO.setSourceType("or");
        PageInfo<ShiporderVO> shiporderVOList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporderAll", shiporderVO);
        List<ShiporderVO> list = shiporderVOList.getList();
        if (list != null && list.size() > 0) {
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            for (int i = 0; i < list.size(); i++) {
                ShiporderVO vo = list.get(i);
                if ("n".equals(vo.getHasTaken()) && "n".equals(vo.getShipStatus())) {
                    vo.setLockStatus("n");
                    // vo.setLockTime(dateString);
                    vo.setUpdateTime(dateString);
                    Shiporder shiporder = new Shiporder();
                    BeanUtils.copyProperties(vo, shiporder);
                    shiporderDAOImpl.updateShiporderLock(shiporder);
                }
            }
            mapResult.put("result", "y");
        } else {
            mapResult.put("result", "y");
        }
        return mapResult;
    }

    /**
     * 系统发货单主表信息插入数据库
     *
     * @param shiporderVO
     * @return
     * @throws Exception
     */
    public int insertSelectiveShiporder(ShiporderVO shiporderVO) throws Exception {
        return shiporderDAOImpl.insertSelectiveShiporder(shiporderVO);
    }

    /**
     * 系统发货单商品明细表信息插入数据库
     *
     * @return
     * @throws Exception
     */
    public int insertSelectiveShiporderSku(ShiporderSkuVO shiporderSkuVO) throws Exception {
        return shiporderSkuDAOImpl.insertSelectiveShiporderSku(shiporderSkuVO);
    }

    @Override
    public int selectCount(Map<String, Object> params) throws Exception {
        return shiporderDAOImpl.selectCount(params);
    }



    @Override
    public int getUnGoingCount(Map<String, String> paramMap) throws Exception {
        return shiporderDAOImpl.unGoingCount(paramMap);
    }
}
